<!--
 * @Author: Cenven
 * @Date: 2021-06-28 10:08:43
 * @Description: 北京泓深教育发展有限公司
 * @Descripttion: 
 * @version: @Lastest
 * @LastEditTime: 2021-09-30 11:00:08
 * @CopyRight: 北京泓深教育发展有限公司
-->
<template>
  <div class="question-detail">
    <div class="breadcrumb">
      <span class="back" @click="$router.push('/question-bank')">题库</span>
      <span class="right-icon"><Icon type="ios-arrow-forward" size="24"/></span>
      <span class="title">{{ title }}</span>
    </div>
    <div class="question_box">
      <div class="question_box_left">
        <img
          :src="
            (questionDetail && questionDetail.cover) ||
              '/img/mobile/question_menus_subject.png'
          "
          alt=""
        />
        <img class="hot_img" src="/img/pc/question_bank_hot.png" alt="" />
      </div>
      <div class="question_box_right">
        <div class="question_name">{{ questionDetail.questionGroupName }}</div>
        <div class="question_center">
          <div class="question_num">
            本测试题共有<span class="q_number">{{
              questionDetail.questionNum
            }}</span
            >道
          </div>
          <div class="student_num">
            已有<span class="s_number">{{ questionDetail.studentSum }}</span
            >人购买
          </div>
        </div>
        <div class="question_date">
          适用限期：{{ questionDetail.startTime }} 至
          {{ questionDetail.endTime }}
        </div>
        <div class="question_price" v-if="!had_question_bank">
          <span>价格：</span>
          <span v-if="isMemberFreeQuestion || (questionDetail && questionDetail.isFree)" class="price"
            >{{isMemberFreeQuestion ? '会员免费' : '免费'}}</span
          >
          <span v-else>
            <template v-if="questionDetail && isDiscount">
              <span class="price"
                ><span class="yen">￥</span
                >{{ questionDetail && questionDetail.discountPrice }}/{{
                  (questionDetail && questionDetail.effectiveTime) || "未知"
                }}年</span
              >
            </template>
            <template v-else>
              <span class="price"
                ><span class="yen">￥</span
                >{{ questionDetail && questionDetail.price }}/{{
                  (questionDetail && questionDetail.effectiveTime) || "未知"
                }}年</span
              >
            </template>
          </span>
          <div class="buy_btn" @click="handleBuy">立即{{ isMemberFreeQuestion || questionDetail.isFree ? "获取" : "购买" }}</div>
        </div>
        <div class="question_btn_list" v-else>
          <div class="to_btn_item" @click="toMyQuestion()">去我的题库</div>
          <div class="to_btn_item" @click="toQuestionTest()">立即答题</div>
        </div>
      </div>
    </div>
    <div class="question_menu">
      <div class="menu_title">包含</div>
      <div class="menu_list">
        <div class="menu_list_item">
          <div class="menu_left">
            <img src="/img/mobile/question_chapter.png" alt="" />
          </div>
          <div class="menu-right">
            <h4>章节练习</h4>
            <p>多练习学得快学得好</p>
          </div>
        </div>
        <div class="menu_list_item">
          <div class="menu_left">
            <img src="/img/mobile/question_special.png" alt="" />
          </div>
          <div class="menu-right">
            <h4>专项训练</h4>
            <p>多练习学得快学得好</p>
          </div>
        </div>
        <div class="menu_list_item">
          <div class="menu_left">
            <img src="/img/mobile/question_simulation.png" alt="" />
          </div>
          <div class="menu-right">
            <h4>模拟考试</h4>
            <p>多练习学得快学得好</p>
          </div>
        </div>
        <div class="menu_list_item">
          <div class="menu_left">
            <img src="/img/mobile/question_wrong.png" alt="" />
          </div>
          <div class="menu-right">
            <h4>我的错题</h4>
            <p>多练习学得快学得好</p>
          </div>
        </div>
        <div class="menu_list_item">
          <div class="menu_left">
            <img src="/img/mobile/question_true.png" alt="" />
          </div>
          <div class="menu-right">
            <h4>真题训练</h4>
            <p>多练习学得快学得好</p>
          </div>
        </div>
        <div class="menu_list_item">
          <div class="menu_left">
            <img src="/img/mobile/question_info.png" alt="" />
          </div>
          <div class="menu-right">
            <h4>考试资讯</h4>
            <p>多练习学得快学得好</p>
          </div>
        </div>
      </div>
    </div>
    <div class="other_hot_question">
      <div class="order_hot_header">
        <span class="head_left">其他热门题库推荐</span>
        <span class="head_right" @click="$router.push('/question-bank')"
          >查看更多<Icon type="ios-arrow-forward" size="14"
        /></span>
      </div>
      <div class="hot_question_list">
        <question-bank-card
          :item="item"
          v-for="(item, index) in questionBankList"
          :key="item.id"
        ></question-bank-card>
      </div>
    </div>
  </div>
</template>

<script>
import { mapState, mapActions, mapMutations } from "vuex";
import {
  getQuestionBankList,
  getQuestionBankOne,
  getCountDownTime,
  saveCountDownTime,
  updateCountDownTime
} from "~/api/v2-question-bank/question-bank";
import { buyQuestionBank } from "~/api/v2-question-bank/order.js";
import QuestionBankCard from "~/components/pc/QuestionBankCard";
export default {
  name: "question-detail",
  components: {
    QuestionBankCard
  },
  data() {
    return {
      questionDetail: {},
      questionBankList: []
    };
  },
  computed: {
    ...mapState({
      user_info(state) {
        return state.user_info;
      },
      is_loading(state) {
        return state.is_loading;
      },
      myQuesionBankList(state) {
        return state.questionBank.question_record_list;
      },
      token(state) {
        return state.token;
      },
      kl_md(state) {
        return state.kl_md;
      },
      member_discount(state) {
        return state.member_discount;
      },
    }),
    // 是否会员免费题库
    isMemberFreeQuestion(){
      if(Object.keys(this.member_discount).length > 0){
        const { deleted , questionGroupIds } = this.member_discount;
        return deleted == 0 && questionGroupIds.includes(Number(this.questionId));
      }else{
        return false;
      }
    },
    title() {
      return this.questionDetail.questionGroupName || "";
    },
    had_question_bank() {
      let result = this.myQuesionBankList.filter(i => i.id == this.questionId && i.deleted != 1);
      if (result && result.length > 0) {
        return true;
      } else {
        return false;
      }
    },
    questionId() {
      return this.$route.query.id;
    },
    isDiscount(){
      if(this.questionDetail.isDiscount == 1){
        let current_time = new Date().getTime();
        let discount_start_time = new Date(this.questionDetail.discountStartTime).getTime();
        let discount_end_time = new Date(this.questionDetail.discountEndTime).getTime();
        return discount_start_time <= current_time && current_time < discount_end_time;
      }else{
        return false;
      }
      
    },
  },
  watch: {},
  methods: {
    ...mapActions(["getMineV2QuestionBankList"]),
    ...mapMutations(["SET_IS_LOADING", "UPDATE_QUESTION_LIST"]),
    toMyQuestion(){
      this.$router.push({
        path: "/classroom?action=myquestion"
      });
    },
    toQuestionTest(){
      this.$router.push({
        path: "/classroom?action=myquestion&questionId="+ this.questionId
      });
    },
    trimDate(date) {
      if (date) {
        let _date = new Date(date);
        return `${_date.getFullYear()}年${_date.getMonth() +
          1}月${_date.getDate()}  ${_date.getHours()}:${_date.getMinutes()}:${_date.getSeconds()}`;
      } else {
        return this.$t("locale.components.mobile.GroupChat.t7");
      }
    },
    /* 购买按钮事件 */
    handleBuy() {
      if (Object.keys(this.user_info).length == 0 || !this.token) {
        this.$router.push({
          path: "/login"
        });
        return;
      }
      const {
        isDiscount,
        discountPrice,
        price,
        discountEndTime,
        discountStartTime,
        isFree,
        questionGroupName,
        startTime,
        endTime,
        isLong
      } = this.questionDetail;
      let params = {
        userId: this.user_info.id,
        questionGroupId: this.questionId,
        ip: returnCitySN.cip
      };
      let current_time = new Date().getTime();
      let discount_start_time = new Date(discountStartTime).getTime();
      let discount_end_time = new Date(discountEndTime).getTime();
      let start_time = new Date(startTime).getTime();
      let end_time = new Date(endTime).getTime();
      let msg = "";

      /* 还未到可以购买的日期 */
      if (current_time < start_time) {
        let _time_ = this.trimDate(start_time);
        this.$Modal.warning({
            title: "提示",
            content: `未到题库开放购买时间哦~  如需购买请等待到${_time_}`
        });
        return;
      } else if (current_time >= end_time) {
        this.$Modal.warning({
            title: "提示",
            content: `已超过题库开放购买时间哦~`
        });
        return;
      }
      if (this.isMemberFreeQuestion || isFree) {
        params = {
          ...params,
          price: 0
        };
        msg = `您确定要获取题库《${questionGroupName}》吗？`;
        this.$Modal.confirm({
          title: "提示",
          content: msg,
          onOk: async () => {
            this.SET_IS_LOADING(true);
            let result = await buyQuestionBank(params);
            // console.log("题库购买：", result);
            if (result && result.data && result.data.code == 200) {
              this.$Message.success("获取成功！");
              this.getMineV2QuestionBankList();
            } else {
              if (result && result.data && result.data.code == 420) {
                this.$Message.warning("余额不足，购买失败!");
              } else if (result && result.data && result.data.code == 1001) {
                this.$Message.error(result.data.msg);
              } else {
                this.$Message.error("购买失败，请稍后重试！");
              }
            }
            this.SET_IS_LOADING(false);
          },
          onCancel: () => {
              // this.$Message.info('Clicked cancel');
          }
        });
      }else{
        this.$router.push({
          path: "/question-purchase?qid="+this.questionId
        });
      }
      return;
      /* 免费 */
      if (isFree) {
        params = {
          ...params,
          price: 0
        };
        msg = `您确定要获取题库《${questionGroupName}》吗？`;
      } else {
        /* 折扣价 */
        if (
          isDiscount == 1 &&
          discount_start_time <= current_time &&
          current_time < discount_end_time
        ) {
          params = {
            ...params,
            price: discountPrice
          };
          /* 原价 */
        } else {
          params = {
            ...params,
            price
          };
        }
        msg = `您确定要支付${params.price}元购买题库《${questionGroupName}》吗？`;
      }
      this.$Modal.confirm({
          title: "提示",
          content: msg,
          onOk: async () => {
              this.SET_IS_LOADING(true);
              let result = await buyQuestionBank(params);
              console.log("题库购买：", result);
              if (result && result.data && result.data.code == 200) {
                this.$Message.success("购买成功！");
                this.getMineV2QuestionBankList();
              } else {
                if (result && result.data && result.data.code == 420) {
                  this.$Message.warning("余额不足，购买失败!");
                } else if (result && result.data && result.data.code == 1001) {
                  this.$Message.error(result.data.msg);
                } else {
                  this.$Message.error("购买失败，请稍后重试！");
                }
              }
              this.SET_IS_LOADING(false);
          },
          onCancel: () => {
              // this.$Message.info('Clicked cancel');
          }
      });
    },
    /* 获取当前题库 */
    async getQuestionBankOne() {
      this.SET_IS_LOADING(true);
      let result = await getQuestionBankOne(this.questionId);
      // console.log("获取当前题库：", result);
      if (result && result.data && result.data.code == 200) {
        const { data } = result.data;
        if (data) {
          this.questionDetail = data;
        }
      }
      this.SET_IS_LOADING(false);
    },
    /* 获取题库列表 */
    async getQuestionBanks() {
      this.SET_IS_LOADING(true);
      let params = {
        offset: 0,
        limit: 4,
        sort: "id desc",
        isDel: 1
      };
      let result = await getQuestionBankList(params);
      if (result && result.data && result.data.code == 200) {
        const { rows, total, records } = result.data.data;
        this.questionBankList = rows;
        this.SET_IS_LOADING(false);
      } else {
        this.SET_IS_LOADING(false);
      }
    }
  },
  created() {
    this.getQuestionBankOne();
    this.getQuestionBanks();
  },
  mounted() {}
};
</script>

<style lang="scss" scoped>
.question-detail {
  width: 1200px;
  margin: 0 auto;
  min-height: 100vh;
  padding-top: 80px;
  padding-bottom: 60px;
  .breadcrumb {
    color: #aaadb3;
    display: flex;
    align-items: center;
    .back {
      font-size: 20px;
      cursor: pointer;
    }
    .right-icon {
      font-size: 20px;
      margin: 0 10px;
    }
    .title {
      font-size: 20px;
      color: #494a4c;
    }
  }
  .question_box {
    width: 1200px;
    height: 380px;
    margin-top: 40px;
    background-color: #ffffff;
    box-sizing: border-box;
    padding: 60px 115px 74px;
    display: flex;
    justify-content: space-between;
    .question_box_left {
      width: 370px;
      height: 246px;
      //   width: 450px;
      //   height: 300px;
      position: relative;
      img {
        width: 100%;
        height: 100%;
        display: block;
        border-radius: 2px;
        overflow: hidden;
      }
      .hot_img {
        position: absolute;
        display: block;
        left: 0;
        top: 0;
        width: 70px;
        height: 60px;
      }
    }
    .question_box_right {
      width: 562px;
      height: 246px;
      .question_name {
        font-size: 18px;
        font-weight: bold;
        line-height: 30px;
        height: 60px;
        // letter-spacing: 2px;
        color: #43474c;
        overflow: hidden;
        -o-text-overflow: ellipsis;
        text-overflow: ellipsis;
        display: -webkit-box;
        -webkit-line-clamp: 2;
        -webkit-box-orient: vertical;
      }
      .question_center {
        display: flex;
        justify-content: space-between;
        align-items: baseline;
        .question_num {
          font-size: 16px;
          font-weight: bold;
          line-height: 30px;
          letter-spacing: 2px;
          color: #8b9199;
          .q_number {
            font-size: 28px;
            letter-spacing: 0px;
            margin: 0 4px;
            color: #5b96ff;
          }
        }
        .student_num {
          font-size: 16px;
          font-weight: bold;
          line-height: 30px;
          letter-spacing: 2px;
          color: #8b9199;
          .s_number {
            font-size: 18px;
            font-weight: bold;
            letter-spacing: 0px;
            color: #ff8a8a;
          }
        }
      }
      .question_date {
        font-size: 14px;
        font-weight: bold;
        margin-top: 6px;
        color: #aaadb3;
        border-bottom: 1px solid #e9ebf0;
        padding-bottom: 40px;
      }
      .question_price {
        display: flex;
        font-size: 16px;
        font-weight: bold;
        line-height: 30px;
        justify-content: flex-end;
        align-items: flex-end;
        color: #494a4d;
        margin-top: 34px;
        .price {
          font-size: 30px;
          font-weight: bold;
          color: #ff8a8a;
          .yen {
            font-size: 16px;
          }
        }
        .buy_btn {
          width: 108px;
          height: 40px;
          background-color: var(--theme-color);
          border-radius: 6px;
          font-size: 16px;
          font-weight: bold;
          color: #ffffff;
          text-align: center;
          line-height: 40px;
          cursor: pointer;
          margin-left: 20px;
        }
      }
      .question_btn_list{
        display: flex;
        font-size: 16px;
        font-weight: bold;
        line-height: 30px;
        justify-content: flex-end;
        align-items: flex-end;
        color: #494a4d;
        margin-top: 34px;
        .to_btn_item{
          height: 40px;
          padding: 0 12px;
          background-color: var(--theme-color);
          border-radius: 6px;
          font-size: 16px;
          font-weight: bold;
          color: #ffffff;
          text-align: center;
          line-height: 40px;
          cursor: pointer;
          margin-left: 20px;
        }
      }
    }
  }
  .question_menu {
    .menu_title {
      font-size: 18px;
      font-weight: bold;
      line-height: 30px;
      color: #43474c;
      margin: 20px 0;
    }
    .menu_list {
      display: flex;
      flex-wrap: wrap;
      .menu_list_item {
        width: 280px;
        height: 130px;
        background-color: #ffffff;
        border-radius: 4px;
        margin: 0 26.666px 26.666px 0;
        box-sizing: border-box;
        padding: 25px 20px;
        display: flex;
        justify-content: space-between;
        // 每行第四个 (4n + 0)
        // 公式（an+ b）.描述：a代表一个循环的大小，N是一个计数器（从0开始），以及b是偏移量。
        &:nth-child(4n) {
          margin: 0 0 26.666px 0;
        }
        // 第四个以上 (1n + 4)
        // &:nth-child(n + 4){
        //     margin: 0 0 26.666px 0;
        // }
        .menu_left {
          width: 80px;
          height: 80px;
          img {
            width: 100%;
            height: 100%;
            display: block;
          }
        }
        .menu-right {
          width: 150px;
          height: 80px;
          h4 {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 20px;
            // font-weight: bold;
            line-height: 40px;
            color: #4a4b4d;
            // margin-top: 10px;
          }
          p {
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            font-size: 16px;
            // font-weight: bold;
            line-height: 40px;
            color: #b1b1b3;
          }
        }
      }
    }
  }
  .other_hot_question {
    .order_hot_header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      box-sizing: border-box;
      padding: 20px 0;
      .head_left {
        font-size: 18px;
        font-weight: bold;
        color: #43474c;
      }
      .head_right {
        font-size: 14px;
        font-weight: bold;
        color: #aaadb3;
        cursor: pointer;
        &:hover {
          color: var(--theme-color);
        }
      }
    }
    .hot_question_list {
      display: flex;
      flex-wrap: wrap;
      width: 100%;
      overflow: hidden;
      justify-content: space-between;
      .question_bank_card:nth-child(4) {
        margin-right: 0;
      }
    }
  }
}
</style>
